<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';

import { ReloadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

import { getFreightIdList, getSendGoodsInfo, updateSendGoodsInfo } from '#/api';
import { auto1688stor } from '#/store';
import { formatMoney, formatMoneyToCent } from '#/utils';

const route = useRoute();
const { shopId } = route.query;

type FormStateType = {
  addPriceOther: number;
  addPricePercentage: number;
  deliveryDelayDay: number;
  freightId: number | string;
  mobile: string;
  startSaleType: number;
  supply7dayReturn: number;
  tbId: number | string;
  cccNo:string;
  creditCode:string;
};

const formState: any = reactive<FormStateType>({
  deliveryDelayDay: 0,
  mobile: '',
  freightId: '',
  startSaleType: 0,
  supply7dayReturn: 0,
  addPricePercentage: 200,
  tbId: '',
  addPriceOther: 10,
  cccNo:null,
  creditCode:null,
});
const dynalightIdList = ref([]);
const loadingGetling = ref(false);
const loadingFetMaxAlls = ref(false);
const auto1688storTres = auto1688stor();
const nowData = computed(() => auto1688storTres.auto1688.nowSelectDyShop);
const dataInxiayou = auto1688storTres.auto1688.bindShopList?.filter(
  (item) => item.pType === 2,
);
onMounted(() => {
  initPageData();
});
function initPageData() {
  if (!nowData.value) return;
  getSendGoodsInfoFunc();
  getFreight();
}
const selectNow = ref(shopId || nowData.value?.shopId);
watch(nowData, (newQuestion, oldQuestion) => {
  if (newQuestion.shopId !== oldQuestion.shopId) {
    // 刷新页面数据
    selectNow.value = newQuestion.shopId;
    initPageData();
  }
});
// 获取店铺的基础设置
function getSendGoodsInfoFunc() {
  if (!nowData.value) return;
  loadingFetMaxAlls.value = true;
  getSendGoodsInfo({ shopId: selectNow.value }).then((res) => {
    Object.keys(res).forEach((key: string) => {
      formState[key] = res[key] as FormStateType;
    });
    formState.addPricePercentage =
      formatMoneyToCent(res.addPricePercentage) || 100;
    loadingFetMaxAlls.value = false;
  });
}

// 获取运费模版
function getFreight() {
  loadingGetling.value = true;

  if (!nowData.value) return;
  getFreightIdList({ shopId: selectNow.value }).then((res) => {
    loadingGetling.value = false;
    dynalightIdList.value = res.list.map((item: any) => item.template);
  });
}
function jumpAddYunfei() {
  open('https://fxg.jinritemai.com/ffa/morder/logistics/freight-list');
}
const fieldNames = {
  label: 'templateName',
  value: 'id',
};
const labelCol = { style: { width: '160px' } };
const buyLink = import.meta.env.VITE_APP_BUY_DOUDIAN_LINK;
function toBuyDYApp() {
  open(buyLink);
}

function saveShopConfig() {
  const saveDataInfo = {
    shopId: nowData.value.shopId,
    addPricePercentage: formatMoney(formState.addPricePercentage) || 1,
    deliveryDelayDay: formState.deliveryDelayDay,
    freightId: formState.freightId,
    mobile: formState.mobile,
    startSaleType: formState.startSaleType,
    supply7dayReturn: formState.supply7dayReturn,
    tbId: formState.tbId,
    addPriceOther: formState.addPriceOther,
    cccNo: formState.cccNo,
    creditCode: formState.creditCode,
  };
  loadingFetMaxAlls.value = true;
  updateSendGoodsInfo(saveDataInfo).then(() => {
    // console.log('保存店铺设置', res);
    message.success('保存成功');
    loadingFetMaxAlls.value = false;
    getSendGoodsInfoFunc();
  });
}
</script>

<template>
  <div v-if="nowData && nowData.shopId" class="px-4 py-4">
    <a-spin :spinning="loadingFetMaxAlls">
      <a-form :label-col="labelCol" :model="formState" layout="inline">
        <a-space direction="vertical">
          <dly-tip-box class="mt-4" title="选择店铺">
            <a-space class="ml-12" direction="vertical">
              <a-form-item label="选择店铺">
             
                <a-select
                  v-model:value="selectNow"
                  :field-names="{
                    label: 'shopName',
                    value: 'shopId',
                  }"
                  :options="dataInxiayou"
                  style="width: 200px"
                  @change="initPageData"
                />
            
              </a-form-item>
            </a-space>
          </dly-tip-box>
          <dly-tip-box title="服务与承诺">
            <a-space class="ml-12" direction="vertical">
              <a-form-item label="客服电话">
                <a-input
                  v-model:value="formState.mobile"
                  maxlength="11"
                  placeholder="请输入客服电话"
                  style="width: 190px"
                />
              </a-form-item>
              <a-form-item label="现货发货时效">
                <a-radio-group v-model:value="formState.deliveryDelayDay">
                  <!-- <a-radio :value="0">当天发货</a-radio> -->
                  <a-radio :value="1">次日发货</a-radio>
                  <a-radio :value="2">48小时发货</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item label="上架设置">
                <a-radio-group v-model:value="formState.startSaleType">
                  <a-radio :value="0">直接上架</a-radio>
                  <a-radio :value="1">放入仓库</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item label="7天无理由设置">
                <a-select
                  v-model:value="formState.supply7dayReturn"
                  style="width: 270px"
                >
                  <a-select-option :value="0">不支持7天无理由</a-select-option>
                  <a-select-option :value="1">支持7天无理由</a-select-option>
                  <a-select-option :value="2">
                    支持7天无理由(拆封后不支持)
                  </a-select-option>
                </a-select>
              </a-form-item>

              <a-form-item label="运费模版">
                <a-select
                  v-model:value="formState.freightId"
                  :field-names="fieldNames"
                  :loading="loadingGetling"
                  :options="dynalightIdList"
                  placeholder="请选择运费模版"
                  style="width: 270px"
                />
                <ReloadOutlined
                  :class="loadingGetling && 'animate-spin'"
                  class="ml-4 cursor-pointer"
                  @click="getFreight"
                />
                <a-button class="ml-4" type="primary" @click="jumpAddYunfei">
                  新建运费模版
                </a-button>
              </a-form-item>


              <a-form-item label="CCC证书编号">
                <a-input
                  v-model:value="formState.cccNo"
                  placeholder="请输入CCC证书编号"
                  style="width: 270px"
                />
              </a-form-item>

              <a-form-item label="企业统一社会信用代码">
                <a-input
                  v-model:value="formState.creditCode"
                  placeholder="请输入社会信用代码"
                  style="width: 270px"
                />
              </a-form-item>
            </a-space>
          </dly-tip-box>


          <dly-tip-box class="mt-4" title="价格库存">
            <a-space class="ml-12" direction="vertical">
              <a-form-item label="商品售价">
            
                <a-space>
                  <a-input-number style="width:200px"
                    v-model:value="formState.addPricePercentage"
                    :max="500"
                    :min="100"
                    addon-after="%"
                    addon-before="代发价X" 
                  />
                  <div>+</div>
                  <a-input-number style="width:120px"
                    v-model:value="formState.addPriceOther"
                    :min="0"
                    addon-after="元"
                  />
                </a-space>

              </a-form-item>
            </a-space>
          </dly-tip-box>
          <a-form-item>
            <a-button
              class="ml-28 mt-24"
              type="primary"
              @click="saveShopConfig"
            >
              保存
            </a-button>
          </a-form-item>
        </a-space>
      </a-form>
    </a-spin>
  </div>
  <div v-else class="px-4 py-4">
    暂未绑定店铺：<a-button type="primary" @click="toBuyDYApp">
      前往绑定
    </a-button>
  </div>
</template>
